﻿package com.longai.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jboss.logging.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import util.Page;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.longai.model.News;
import com.longai.model.UploadFileInfo;
import com.longai.service.FileUpload;
import com.longai.service.NewsService;

import functions.Px;

@Controller
@RequestMapping("new")
public class NewsAction {
    @Autowired
	NewsService newsService;
    FileUpload fileupload;
    @RequestMapping(value = "newsList",method = RequestMethod.GET)//获取心灵鸡汤列表
	@ResponseBody
	public Object newslist(@RequestParam("currentPage")String currentPage
			,@RequestParam("amount")String amount){
		Page news=newsService.findNewsAll(currentPage,amount);
		List<News> list = new ArrayList<News>();
		List<News> lsList = news.getList();
		for(News  so:lsList){
			so.setCover(Px.px("newsImage")+so.getCover());
			list.add(so);
		}
		news.setList(list);
		return news;
	}
	@RequestMapping("newManager")//跳转到心灵鸡汤管理界面
	public String newManager(Model model){
		List<News> news=newsService.findAll();
		model.addAttribute("news",news);
		return "newManager";
	}
	@RequestMapping("addNew")//跳转到心灵鸡汤编辑界面
	public String addNew(String newsId,Model model){
		if(newsId==null)
			return "addNew";
		else{
		int num=Integer.parseInt(newsId);
		News news=newsService.findById(num);
		model.addAttribute("newss", news);
		return "addNew";
		}
	}
	@RequestMapping("addNewEdit")//修改或者新增心灵鸡汤
	public String addNewEdit(News news,@RequestParam("image")MultipartFile cover,HttpServletRequest request){
		try {
			UploadFileInfo uploadFileInfo =  fileupload.upload(cover, "newsImage", request);
			if(uploadFileInfo.isStatus()){	
				news.setCover(uploadFileInfo.getName());
				//System.out.println(uploadFileInfo.getName());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		newsService.save(news);
		return "redirect:newManager";
	}
	@RequestMapping("deleteNew")//根据id删除心灵鸡汤
	public String deleteNew(News news){
		newsService.delete(news);
		return "redirect:newManager";
	}
}
